package com.zzti.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.zzti.pojo.OrderServer;
import com.zzti.pojo.SysResult;
import com.zzti.pojo.Visiter;
import com.zzti.pojo.Waiter;
import com.zzti.serviceImpl.OrderServerServiceImpl;
import com.zzti.serviceImpl.VisiterServiceImpl;
import com.zzti.serviceImpl.WaiterServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RequestMapping("/waiter")
@Controller
public class WaiterController {
    @Autowired
    private WaiterServiceImpl waiterServiceImpl;
    @Autowired
    private VisiterServiceImpl visiterServiceImpl;
    @Autowired
    private OrderServerServiceImpl orderServerServiceImpl;

    @RequestMapping("/findAll")
    @ResponseBody
    public String findAll(@RequestParam("limit") Integer limit, @RequestParam("page") Integer page, HttpServletRequest request,
                          @RequestParam(name = "waiterName", required = false, defaultValue = "") String waiterName) {
        Map<String, Object> ret = new HashMap<>();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("waiterName", waiterName);
        List<Waiter> aaa = waiterServiceImpl.findAll(queryMap);
        queryMap.put("page", (page - 1) * limit);
        queryMap.put("limit", limit);
        JSONArray ja = new JSONArray();
        List<Waiter> ls = waiterServiceImpl.findAll(queryMap);
        return JSON.toJSONString(SysResult.success(ls, WaiterServiceImpl.count));
    }

    @RequestMapping("/findAll2")
    @ResponseBody
    public String findAll2(Integer page, int limit, HttpServletRequest request,
                           @RequestParam(name = "roleName", required = false, defaultValue = "") String roleName) {
        Map<String, Object> queryMap = new HashMap<>();

        queryMap.put("roleName", roleName);
        List<Waiter> aaa = waiterServiceImpl.findAll2(queryMap);
        queryMap.put("page", (page - 1) * limit);
        queryMap.put("limit", limit);
        List<Waiter> all = waiterServiceImpl.findAll2(queryMap);
        String s = JSON.toJSONString(all);

        return "{\"count\":" + aaa.size() + ", \"code\":0 , \"data\":" + s + "}";
    }

    @ResponseBody
    @RequestMapping("/purchase")
    public String wdhass(Double price, Integer userId, Integer waiterId, Integer number, String address) {
        Visiter vis = visiterServiceImpl.findOne(userId);
        Waiter w = waiterServiceImpl.findOne(waiterId);
        Double now = vis.getMoney();
        if (price * number > now) {
            return JSON.toJSONString(SysResult.fail("余额不足,请充值"));
        }
        if (price * number <= now) {
            vis.setMoney(now - price * number);
            visiterServiceImpl.update(vis);
            orderServerServiceImpl.add(userId, waiterId, number, price, 0, address);
            w.setIsFree(0);
            waiterServiceImpl.update(w);
            WaiterAutoUpdate(w);
            return JSON.toJSONString(SysResult.success("购买成功"));
        }
        return "";
    }

    public void WaiterAutoUpdate(Waiter w) {
        OrderServer os = orderServerServiceImpl.findOne(w.getId());
        Date date = os.getCreateTime();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, date.getHours()); // 控制时
        calendar.set(Calendar.MINUTE, date.getMinutes());       // 控制分
        calendar.set(Calendar.SECOND, date.getSeconds() + os.getNumber());       // 控制秒
        Date time = calendar.getTime();         // 得出执行任务的时间
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                w.setIsFree(1);
                waiterServiceImpl.update(w);
                os.setStatus(1);
                orderServerServiceImpl.update(os);
            }
        }, time, 1000 * 60 * 60 * 24);
    }

    @ResponseBody
    @RequestMapping("/findById")
    public SysResult findById(Integer id) {

        Waiter wait = waiterServiceImpl.findOneWaiter(id);
        System.out.println(wait);
        if (wait == null) {
            return SysResult.fail("没有找到此人");
        }
        return SysResult.success(wait);
    }


    @RequestMapping("/insert")
    @ResponseBody
    public SysResult insert(Waiter waiter) {

        Waiter wait = new Waiter(null, waiter.getAccount(), waiter.getName(), waiter.getAge(), waiter.getSex(), null, null, null, waiter.getAddress(),
                waiter.getPhone(), waiter.getSalary(), null, waiter.getPassword(), waiter.getPrice(), waiter.getIsFree(), waiter.getComment(), 0, null);

        Integer add = waiterServiceImpl.add(wait);
        if (add > 0)
            return SysResult.success();
        else
            return SysResult.fail();
    }

    @RequestMapping("/update")
    @ResponseBody
    public SysResult update(Waiter waiter) {

        Waiter wait = new Waiter(waiter.getId(), waiter.getAccount(), waiter.getName(), waiter.getAge(), waiter.getSex(), null, null, null, waiter.getAddress(),
                waiter.getPhone(), waiter.getSalary(), null, waiter.getPassword(), waiter.getPrice(), waiter.getIsFree(), waiter.getComment(), null, null);

        Integer up = waiterServiceImpl.update(wait);
        if (up > 0)
            return SysResult.success();
        else
            return SysResult.fail();
    }

    @RequestMapping("/queryById/{id}")
    public String queryById(@PathVariable("id") Integer id, Model model) {

        Waiter wait = waiterServiceImpl.findOneWaiter(id);
        System.out.println(wait);
        model.addAttribute("wai", wait);

        return "view/role/role-form.html";
    }

    @RequestMapping("/delete/{id}")
    @ResponseBody
    public SysResult deleteById(@PathVariable("id") Integer[] ids) {
        //System.out.println(ids);
        if (waiterServiceImpl.deleteByIds(ids) > 0)
            return SysResult.success();
        else
            return SysResult.fail();
    }
}

